import React, { PureComponent } from 'react';
import { Modal, Form, Select, Input, Upload, message, Icon, Button, DatePicker, Row, Col, Radio, Tag } from 'antd';
import PropTypes from 'prop-types';
import styles from '../../../components/common/PateoTable/TableList.less';
import MapSearch from "../../../components/MapSearch/MapSearch";
import AddressHistoryModal from "./addressHistoryModal"
import { getDicByCodeSort, getDicByCodeSortRadio, getDicByKey } from '@/support/common';
import { connect } from 'dva';
import { getToken } from '@/utils/utils';
import { getOptAuthHeaders } from '@/utils/common'

const styleRequired = {
  display: 'inline-block',
  marginRight: '4px',
  content: '*',
  fontFamily: 'SimSun',
  lineHeight: '1',
  fontSize: '14px',
  color: '#f5222d',
}
const reg = [
  '',
  /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|[xX])$/,
  /^[a-zA-Z0-9]{5,17}$/,
  /^(南字第(\d{8})|北字第(\d{8})|沈字第(\d{8})|兰字第(\d{8})|成字第(\d{8})|济字第(\d{8})|广字第(\d{8})|海字第(\d{8})|空字第(\d{8})|参字第(\d{8})|政字第(\d{8})|后字第(\d{8})|装字第(\d{8}))号{1}$/,
  /^((\d{4,20})|([\u4e00-\u9fa5]+字第(\d+|\d+-\d+)))号?$/,
  /[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}/,
  /^[HMhm]{1}([0-9]{10}|[0-9]{8})$/,
  /^[0-9]{10}$/,
];
const RadioGroup = Radio.Group;
const FormItem = Form.Item;
const { TextArea } = Input;
@connect(state => ({
  menu: state.menu
}))
// @Form.create()
export default class VehicleActiveModal extends PureComponent {
  static contextTypes = {
    dicData: PropTypes.any,
  };
  state = {
    previewVisible: false,
    previewImage: '',
    fileList: [],
    buttonLoading: false,
    phoneVal: '',
    url2List: [],
    fullFaceUrlList: [],
    backViewUrlList: [],
    handPhotoUrlList: [],
    businessLicenseUrlList: [],
    count: 0,
    originPhone: '',
    mapVisible: false,
    subDealerAddressVisible: { display: 'none' },
    lng: '',
    lat: '',
  };

  componentWillMount() {
  }

  componentDidMount() {
    this.props.onRef(this);
  }
  componentWillReceiveProps() {
  }
  getLabel = (lable) => <span><span style={styleRequired}>* </span>{lable}</span>;

  setStateData = (data) => {
    this.setState({
      ...data,
    })
  }

  setData = (data) => {
    if (data.length === 1) {
      const list = [];
      let obj = { uid: -1, url: data[0] };
      list.push(obj);
      this.setState({
        fileList: list,
      });
    } else if (data.length === 4) {
      data.map((item, index) => {
        const list = [];
        let obj = { uid: -1, url: item }
        list.push(obj);
        if (index === 0) {
          this.setState({
            url2List: list,
          });
        } else if (index === 1) {
          this.setState({
            fullFaceUrlList: list,
          });
        } else if (index === 2) {
          this.setState({
            backViewUrlList: list,
          });
        } else if (index === 3) {
          this.setState({
            handPhotoUrlList: list,
          });
        }
      })
    } else if (data.length === 5) {
      data.map((item, index) => {
        const list = [];
        let obj = { uid: -1, url: item }
        list.push(obj);
        if (index === 0) {
          this.setState({
            url2List: list,
          });
        } else if (index === 1) {
          this.setState({
            fullFaceUrlList: list,
          });
        } else if (index === 2) {
          this.setState({
            backViewUrlList: list,
          });
        } else if (index === 3) {
          this.setState({
            handPhotoUrlList: list,
          });
        } else if (index === 4) {
          this.setState({
            businessLicenseUrlList: list,
          });
        }
      })
    }
  }
  setPhone = (value) => {
    this.setState({
      phoneVal: value,
    });
  }
  setPhoneVal = (e) => {
    this.setState({
      phoneVal: e.target.value,
    });
  }
  ok = (e) => {
    // e.preventDefault();
    const { form, handleCloseActive, dispatch, page, formValues, reActiveFlag, qualityUserMap } = this.props;
    const { fileList, url2List, fullFaceUrlList,
    backViewUrlList, handPhotoUrlList, businessLicenseUrlList } = this.state;
    this.refs.form.validateFields().then(((fieldsValue)=>{
    console.log('values', fieldsValue)
    this.setState({
      buttonLoading: true,
    });
    const obj = fieldsValue;
    console.log('obj', obj);
    if (reActiveFlag) {
      obj.declarer = fieldsValue.declarerOther;
      if (fieldsValue.activeType === "1") {
        if (fieldsValue.url2) {
          obj.url = fieldsValue.url2.file.response.url;
        } else {
          obj.url = url2List[0].url;
        }
        if (fieldsValue.fullFaceUrl) {
          obj.fullFaceUrl = fieldsValue.fullFaceUrl.file.response.url;
        } else {
          obj.fullFaceUrl = fullFaceUrlList[0].url;
        }
        if (fieldsValue.backViewUrl) {
          obj.backViewUrl = fieldsValue.backViewUrl.file.response.url;
        } else {
          obj.backViewUrl = backViewUrlList[0].url;
        }
        if (fieldsValue.handPhotoUrl) {
          obj.handPhotoUrl = fieldsValue.handPhotoUrl.file.response.url;
        } else {
          obj.handPhotoUrl = handPhotoUrlList[0].url;
        }
      } else if (fieldsValue.activeType === "2") {
        if (fieldsValue.url2) {
          obj.url = fieldsValue.url2.file.response.url;
        } else {
          obj.url = url2List[0].url;
        }
        if (fieldsValue.fullFaceUrl) {
          obj.fullFaceUrl = fieldsValue.fullFaceUrl.file.response.url;
        } else {
          obj.fullFaceUrl = fullFaceUrlList[0].url;
        }
        if (fieldsValue.backViewUrl) {
          obj.backViewUrl = fieldsValue.backViewUrl.file.response.url;
        } else {
          obj.backViewUrl = backViewUrlList[0].url;
        }
        if (fieldsValue.handPhotoUrl) {
          obj.handPhotoUrl = fieldsValue.handPhotoUrl.file.response.url;
        } else {
          obj.handPhotoUrl = handPhotoUrlList[0].url;
        }
        if (fieldsValue.businessLicenseUrl) {
          obj.businessLicenseUrl = fieldsValue.businessLicenseUrl.file.response.url;
        } else {
          obj.businessLicenseUrl = businessLicenseUrlList[0].url;
        }
      } else {
        if(fieldsValue.activeType === "3") {
          const { lng, lat } = this.state;
          //二网展车
          if(lng&&lat&&obj.subDealerAddress) {
            obj.subDealerLon = lng;
            obj.subDealerLat = lat;
          }
        }

        // if (fieldsValue.url1) {
        //   obj.url = fieldsValue.url1.file.response.url;
        // } else {
        //   obj.url = fileList[0].url;
        // }
      }
    } else {
      if (fieldsValue.activeType === "1" ) {
        obj.url = fieldsValue.url2.file.response.url;
        obj.fullFaceUrl = fieldsValue.fullFaceUrl.file.response.url;
        obj.backViewUrl = fieldsValue.backViewUrl.file.response.url;
        obj.handPhotoUrl = fieldsValue.handPhotoUrl.file.response.url;
        obj.declarer = fieldsValue.declarerOther;
      } else if (fieldsValue.activeType === "2") {
        obj.url = fieldsValue.url2?.file.response.url;
        obj.fullFaceUrl = fieldsValue.fullFaceUrl?.file.response.url;
        obj.backViewUrl = fieldsValue.backViewUrl?.file.response.url;
        obj.handPhotoUrl = fieldsValue.handPhotoUrl?.file.response.url;
        obj.businessLicenseUrl = fieldsValue.businessLicenseUrl?.file.response.url;
        obj.declarer = fieldsValue.declarerOther;
      } else if (fieldsValue.activeType === "6" ) {
        obj.declarer = qualityUserMap.get(fieldsValue.declarerQuality) ? qualityUserMap.get(fieldsValue.declarerQuality) : '';
      } else {
        if(fieldsValue.activeType === "3") {
          const { lng, lat } = this.state;
          //二网展车
          if(lng&&lat&&obj.subDealerAddress) {
            obj.subDealerLon = lng;
            obj.subDealerLat = lat;
          }
        }
        // obj.url = fieldsValue.url1.file.response.url;
        obj.declarer = fieldsValue.declarerOther;
      }
    }
    if (fieldsValue.captcha) {
      this.props.dispatch({
        type: 'vehicle/checkVerifCode',
        payload: {
          phone: fieldsValue.phone,
          code: fieldsValue.captcha,
        },
        callback: (data) => {
          if (data.code === '0') {
            obj.batchType = 1; //批量类型，1-单个，2-批量
            dispatch({
              type: 'vehicle/activeApply',
              payload: obj,
              callback: (response) => {
                if (response.code === '200') {
                  if (obj.activeType === '4' || obj.activeType === '5'|| obj.activeType === '6' || obj.activeType === '3' || obj.activeType === '9') {
                    message.success('激活成功');
                  } else if (obj.activeType === '1' || obj.activeType === '2') {
                    message.success('提交成功');
                  }
                  dispatch({
                    type: 'vehicle/fetch',
                    payload: {
                      page: page.current - 1,
                      size: page.pageSize,
                      ...formValues,
                    },
                  });
                  this.setState({
                    phoneVal: '',
                    fileList: [],
                    buttonLoading: false,
                    subDealerAddressVisible: { display: 'none' },
                    lng : '',
                    lat: '',
                  });
                  this.refs.form.resetFields();
                  handleCloseActive();
                  if(this.interval){
                    window.clearInterval(this.interval);
                    this.interVal = null;
                    }
                    this.setState({ count: 0 });
                } else {
                  if (response.code === '500') {
                    message.error(response.description);
                  } else {
                    message.error('激活失败');
                  }
                  this.setState({
                    buttonLoading: false,
                  });
                }
              },
            });
          } else {
            message.error(data.description);
            this.setState({
              buttonLoading: false,
            });
          }
        },
      });
    } else {
      obj.batchType = 1; //批量类型，1-单个，2-批量
      dispatch({
        type: 'vehicle/activeApply',
        payload: obj,
        callback: (response) => {
          if (response.code === '200') {
            if (obj.activeType === '4' || obj.activeType === '5'|| obj.activeType === '6' || obj.activeType === '3' || obj.activeType === '9') {
              message.success('激活成功');
            } else if (obj.activeType === '1' || obj.activeType === '2') {
              message.success('提交成功');
            }
            dispatch({
              type: 'vehicle/fetch',
              payload: {
                page: page.current - 1,
                size: page.pageSize,
                ...formValues,
              },
            });
            this.setState({
              phoneVal: '',
              fileList: [],
              buttonLoading: false,
              subDealerAddressVisible: { display: 'none' },
              lng : '',
              lat: '',
            });
            this.refs.form.resetFields();
            handleCloseActive();
            if(this.interval){
              window.clearInterval(this.interval);
              this.interVal = null;
              }
              this.setState({ count: 0 });
          } else {
            if (response.code === '500') {
              message.error(response.description);
            } else {
              message.error('激活失败');
            }
            this.setState({
              buttonLoading: false,
            });
          }
        },
      });
    }
  }))
  };

  checkTemplateFile = (rule, value, callback) => {
    const { type } = this.props;
    const { fileList } = this.state;
    // if (fileList.length === 0 && (type === '3'|| type === '4'||
    //     type === '5')) {
    //   callback('请上传工作联络单');
    //   return;
    // }
    callback();
  }

  checkUrl2 = (rule, value, callback) => {
    const { type } = this.props;
    const { url2List } = this.state;
    if (url2List.length === 0  && (type === '1' || type === '2')) {
      callback('请上传购车发票');
      return;
    }
    callback();
  }

  checkFullFaceUrl = (rule, value, callback) => {
    const { type } = this.props;
    const { fullFaceUrlList } = this.state;
    if (fullFaceUrlList.length === 0  && (type === '1' || type === '2')) {
      callback('请上传证件正面');
      return;
    }
    callback();
  }

  checkBackViewUrl = (rule, value, callback) => {
    const { type } = this.props;
    const { backViewUrlList } = this.state;
    if (backViewUrlList.length === 0  && (type === '1' || type === '2')) {
      callback('请上传证件反面');
      return;
    }
    callback();
  }

  checkHandPhotoUrl = (rule, value, callback) => {
    const { type } = this.props;
    const { handPhotoUrlList } = this.state;
    if (handPhotoUrlList.length === 0  && (type === '1' || type === '2')) {
      callback('请上传手持证件');
      return;
    }
    callback();
  }

  checkBusinessLicenseUrl = (rule, value, callback) => {
    const { type } = this.props;
    const { businessLicenseUrlList } = this.state;
    if (businessLicenseUrlList.length === 0  && (type === '2')) {
      callback('请上传营业执照');
      return;
    }
    callback();
  }

  checkCertType = (rule, value, callback) => {
    const { type } = this.props;
    if ((type === '1' || type === '2') && !value) {
      callback('请选择证件类型');
      return;
    }
    callback();
  }

  checkCertNo = (rule, value, callback) => {
    const { type } = this.props;
    if ((type === '1' || type === '2')) {
      if (value) {
        const { certType } = this.refs.form.getFieldsValue(['certType']);
        const regex = new RegExp(reg[parseInt(certType)]);
        if(!regex.test(value)){
          callback('请填写正确的证件号码');
          return;
        }
      } 
    }
    // if ((type === '1' || type === '2')) {
    //   if (value) {
    //     const { certType } = this.refs.form.getFieldsValue(['certType']);
    //     const regex = new RegExp(reg[parseInt(certType)]);
    //     if(!regex.test(value)){
    //       callback('请填写正确的证件号码');
    //       return;
    //     }
    //   } else {
    //     callback('请填写证件号码');
    //     return;
    //   }
    // }
    callback();
  }

  checkDeclarerQuality = (rule, value, callback) => {
    const { qualityVisible } = this.props;
    if (!qualityVisible['display'] && !value) {
      callback('请填写申请人姓名');
      return;
    }
    callback();
  }

  checkDeclarerOther = (rule, value, callback) => {
    const { declarerVisible } = this.props;
    if (!declarerVisible['display'] && !value) {
      callback('请填写申请人姓名');
      return;
    }
    callback();
  }

  checkAddress = (rule, value, callback) => {
    const { type } = this.props;
    if ((type === '1' || type === '2') && !value) {
      callback('请填写地址');
      return;
    }
    callback();
  }

  checkSex = (rule, value, callback) => {
    const { type } = this.props;
    if ((type === '1' || type === '2') && !value) {
      callback('请填写性别');
      return;
    }
    callback();
  }

  checkCaptcha = (rule, value, callback) => {
    const { codeVisible } = this.props;
    if (!codeVisible.display && !value) {
      callback('请输入验证码!');
      return;
    }
    callback();
  }

  checkDate = (rule, value, callback) => {
    const { type } = this.props;
    if ((type === '3'|| type === '4'||
        type === '5' || type === '6')  && !value) {
      callback('请选择截止时间');
      return;
    }
    callback();
  }

  checkPhone = (rule, value, callback) => {
    const { type } = this.props;
    if (type === '3' && (value !== this.state.phoneVal)) {
      callback('请确认电话号码');
      return;
    }
    callback();
  }

  checkDealer = (rule, value, callback) => {
    const { activeDealerVisible } = this.props;
    if (!activeDealerVisible['display'] && !value) {
      callback('请选择经销商');
      return;
    }
    callback();
  }

  checkSubDealer = (rule, value, callback) => {
    const { type } = this.props;
    if (type === '3' && value === undefined) {
      callback('请选择是否为二网车辆');
      return;
    }
    callback();
  }

  checkSubDealerAddress = (rule, value, callback) => {
    const { type } = this.props;
    const { subDealer } = this.refs.form.getFieldsValue(['subDealer']);
    if (type === '3' && subDealer && !value) {
      callback('请选择二网地址');
      return;
    }
    callback();
  }



  close = () => {
    if(this.interval){
      window.clearInterval(this.interval);
      this.interVal = null;
      }
    const { handleCloseActive, form } = this.props;
    this.setState({
      fileList: [],
      phoneVal: '',
      buttonLoading: false,
      subDealerAddressVisible: { display: 'none' },
      lng : '',
      lat: '',
      count: 0,
    });
    this.refs.form.resetFields();
    handleCloseActive();
  }
  disabledDate = (current) => {
    // can not select days before today and today
    return current && (current.valueOf() < (Date.now() - (24 * 60 * 60 * 1000))
      || current.valueOf() > (Date.now() + (364 * 24 * 60 * 60 * 1000)));
  }
  disabledDeadlineDate = (current) => {//激活为质检车，截止时间范围为两周
    // can not select days before today and today
    return current && (current.valueOf() < (Date.now() - (24 * 60 * 60 * 1000))
      || current.valueOf() > (Date.now() + (14 * 24 * 60 * 60 * 1000)));
  }
  handleDel = () => {
    this.setState({
      fileList: [],
      url2List: [],
      fullFaceUrlList: [],
      backViewUrlList: [],
      handPhotoUrlList: [],
      businessLicenseUrlList: [],
    });
  }
  handleCancel = () => this.setState({ previewVisible: false })

  handlePreview = (file) => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  }

  handleCertTypeChange = () => {
    this.refs.form.resetFields(['certNo']);
  }

  handleChange = (info) => {
    let { fileList } = info;
    fileList = fileList.slice(-1);
    if (info.file.status === 'done' && info.file.response && info.file.response.error === 0) {
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    } else if (!info.file.status) {
      this.setState({
        fileList: [],
      });
      return;
    }
    this.setState({ fileList: fileList });
  }

  handleUrl2Change = (info) => {
    let { fileList } = info;
    fileList = fileList.slice(-1);
    if (info.file.status === 'done' && info.file.response && info.file.response.error === 0) {
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    } else if (!info.file.status) {
      this.setState({
        url2List: [],
      });
      return;
    }
    this.setState({ url2List: fileList });
  }

  handleFullFaceUrlChange = (info) => {
    let { fileList } = info;
    fileList = fileList.slice(-1);
    if (info.file.status === 'done' && info.file.response && info.file.response.error === 0) {
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    } else if (!info.file.status) {
      this.setState({
        fullFaceUrlList: [],
      });
      return;
    }
    this.setState({ fullFaceUrlList: fileList });
  }

  handleBackViewUrlChange = (info) => {
    let { fileList } = info;
    fileList = fileList.slice(-1);
    if (info.file.status === 'done' && info.file.response && info.file.response.error === 0) {
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    } else if (!info.file.status) {
      this.setState({
        backViewUrlList: [],
      });
      return;
    }
    this.setState({ backViewUrlList: fileList });
  }

  handleHandPhotoUrlChange = (info) => {
    let { fileList } = info;
    fileList = fileList.slice(-1);
    if (info.file.status === 'done' && info.file.response && info.file.response.error === 0) {
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    } else if (!info.file.status) {
      this.setState({
        handPhotoUrlList: [],
      });
      return;
    }
    this.setState({ handPhotoUrlList: fileList });
  }

  handleBusinessLicenseUrlChange = (info) => {
    let { fileList } = info;
    fileList = fileList.slice(-1);
    if (info.file.status === 'done' && info.file.response && info.file.response.error === 0) {
      message.success(`${info.file.name} 上传成功`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败`);
    } else if (!info.file.status) {
      this.setState({
        businessLicenseUrlList: [],
      });
      return;
    }
    this.setState({ businessLicenseUrlList: fileList });
  }

  beforeUpload = (file) => {
    if (file.type === 'image/jpeg' || file.type === 'image/png') {
      if (file.size / 1024 / 1024 > 5) {
        message.error('图片大小不能大于5MB!');
        return false;
      }
      return true;
    } else {
      message.error('请上传JPG或PNG格式图片！');
      return false;
    }
  }

  resetPhone = () => {
    this.setState({
      phoneVal: '',
    });
  }

  // 发送验证码
  onGetCaptcha = () => {
    // const { form: { validateFields } } = this.props;
    const { form,dispatch } = this.props;
    const { vin, phone } = this.refs.form.getFieldsValue(['vin','phone']);
    this.refs.form.validateFields(['phone'], { force: true }, ).then(((fieldsValue)=>{ 
      dispatch({
        type: 'vehicle/findVerificationCodeByVin',
        payload: {
          vin,
          phone,
        },
        callback: (data) => {
          if (data.code === '0') {
            message.success('发送成功');
            this.state.verif = true;
            let count = 60;
            if (!this.interVal) {
            this.interval = window.setInterval(() => {
              count--;
              // count -= 1;
              this.setState({count});
              if (count === 0) {
                window.clearInterval(this.interval);
                this.interVal = null;
              }
            }, 1000);
            }
          } else {
            message.error(data.description);
          }
        },
      });
    }))
    // validateFields(['phone'], { force: true },
    //   (err, params) => {
    //     if (!err) {
    //       console.log('11111')
    //       dispatch({
    //         type: 'vehicle/findVerificationCodeByVin',
    //         payload: {
    //           vin,
    //           phone,
    //         },
    //         callback: (data) => {
    //           if (data.code === '0') {
    //             message.success('发送成功');
    //             this.state.verif = true;
    //             let count = 60;
    //             this.interval = setInterval(() => {
    //               count -= 1;
    //               this.setState({count});
    //               if (count === 0) {
    //                 clearInterval(this.interval);
    //               }
    //             }, 1000);
    //           } else {
    //             message.error(data.description);
    //           }
    //         },
    //       });
    //     }
    //   }
    // );
  };

  checkCode = (phone,code) => {
    this.props.dispatch({
      type: 'vehicle/checkVerifCode',
      payload: {
        phone,
        code,
      },
      callback: (data) => {
        if (data.code === '0') {
          this.setState({ flag: data.code });
        } else {
          this.setState({ flag: data.description});
        }
      },
    });
  }

  setOriginPhone = (value) => {
    this.setState({ originPhone: value})
  }

  onChangePhone = (e) => {
    const { reActiveFlag, setCodeVisible } = this.props;
    const { originPhone } = this.state;
    if (reActiveFlag) {
      if (e.target.value !== originPhone) {
        setCodeVisible({});
      } else {
        setCodeVisible({ display: 'none' });
      }
    }
  }

  onDeclarerChange = (value) => {
    const { phoneMap, form } = this.props;
    this.refs.form.setFieldsValue({ phone: phoneMap.get(Number(value))  });
  }

  getAddress = (address,lng,lat) => {
    const { form } = this.props;
    this.refs.form.setFieldsValue({ subDealerAddress: address });
    this.setState({
      lng,
      lat,
    })
  };

  onRadioChange = (info) => {
    const { form } = this.props;
    this.refs.form.resetFields(['subDealerAddress']);
    this.setState({
      lng : '',
      lat: '',
    })
    if (info && info.target) {
      if (info.target.value === true) {
        this.setState({
          subDealerAddressVisible: { marginBottom: 10, marginTop: -15 },
        });
      } else if (info.target.value === false) {
        this.setState({
          subDealerAddressVisible: { display: 'none' },
        });
      }
    }
  }

  handleHistoryAddress = () => {
    const { dispatch,currentUser,form } = this.props
    // const { levelCode } = currentUser;
    const {menu: { userProfile, dataPermission}} = this.props;
    let obj = {
      dealerCode: 'aaa'
    };
    const {orgNo} = this.refs.form.getFieldsValue(['orgNo']);
    if(orgNo){
      obj.dealerCode = orgNo;
    }
    // if (levelCode) {
    //   if (levelCode.split('-').length === 2) {
    //     const {orgNo} = this.refs.form.getFieldsValue(['orgNo']);
    //     if(orgNo) {
    //       obj.dealerCode = orgNo;
    //     } else {
    //       obj.dealerCode = levelCode;
    //     }
    //   } else if (levelCode.split('-').length === 4) {
    //     obj.dealerCode = levelCode.split('-')[3];
    //   }
    // }
    dispatch({
      type: 'extendForm/fetch',
      payload: { url: '/vehicle/subDealerList', ...obj },
      callback: (response) => {
        if(response.code === '200') {
          this.address.setStateData({
            list: response.data,
          });
          this.address.handleOpen();
        } else {
          message.error(response.description);
        }

      }
    })
  }

  handleSetAddress = (record) => {
    const { form } = this.props;
    if(record&&record.address&&record.lon&&record.lat) {
      this.refs.form.setFieldsValue({ subDealerAddress: record.address });
      this.setState({
        lng: record.lon,
        lat: record.lat
      })
    }
  }
  componentWillUnmount() {
    if(this.interval){
    window.clearInterval(this.interval);
    this.interVal = null;
    }
  }

  renderSimpleForm() {
    const { previewVisible, previewImage,
      fileList, buttonLoading,
      url2List,fullFaceUrlList,backViewUrlList,
      handPhotoUrlList, businessLicenseUrlList, count, mapVisible, subDealerAddressVisible } = this.state;
    // const certTypeOptions = getDicByCodeSort(this.context.dicData, 'certType');
    // const sexRadio = getDicByCodeSortRadio(this.context.dicData, 'activeSex');
    const domain = window.g.url;
    const url = '/common/upload/img';
    const str = `${domain}${url}`;

    const urlCompress = '/common/upload/img';
    const fullFaceStr = `${domain}${urlCompress}`;
    const backViewStr =`${domain}${urlCompress}`;
    const handPhotoStr =`${domain}${urlCompress}`;
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">点击上传</div>
      </div>
    );
    const uploadButton1 = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传图片</div>
      </div>
    );
    const { activeVisible, typeOptions, title,
      label, handelSelect, inputVisible,
      dateVisible, phoneVisible, activeDealerOptions,
      activeDealerVisible, uploadUrlVisible,
      urlsVisible, activeFileUrl, modelVisible,
      activeTypeDisabled, businessLicenseVisible,
      codeVisible, phoneDisable,
      qualityUserOptions, qualityVisible,
      declarerVisible, remarksDesc, realNameDisable, showUploadList, subDealerVisible } = this.props;
    const newOptions = typeOptions.filter(item => item.key !== '7');
    const {menu: { userProfile, dataPermission,permissions}} = this.props;
    const isDeadlineDisable = permissions.includes("/deviceManager/vehicle/vehicle-deadline");//是否为S31用户
    const deadlineDisable = phoneDisable && isDeadlineDisable;
    // const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 16 },
      },
    };
    return (
      <div>
        <Modal
          title={title}
          // okText="保存"
          visible={activeVisible}
          // onOk={this.ok}
          onCancel={this.close}
          footer={[
            <Button key="back" size="default" onClick={this.close}>
              取消
            </Button>,
            <Button loading={buttonLoading} key="save" type="primary" size="default" onClick={() => this.refs.form.submit()}>
              保存
            </Button>,
          ]}
        >
          <div id="activeForm">
            <Form
              // onSubmit={this.handleSubmit}
              onFinish={this.ok}
              //hideRequiredMark
              style={{ marginTop: 5 }}
              ref="form"
            >
              <div style={{marginBottom:'10px'}}>
                <span style={{color: 'red'}}>{remarksDesc ? remarksDesc : ''}</span>
              </div>
              <FormItem
                {...formItemLayout}
                label="VIN号"
                name="vin"
                rules={[
                  { required: false, message: '' },
                ]}
              >
                <Tag color="blue">{this.refs.form ? this.refs.form.getFieldsValue(['vin']).vin : ''}</Tag>
              </FormItem>
              <FormItem
                style={activeDealerVisible}
                {...formItemLayout}
                label="经销商"
                name="orgNo"
                rules={[
                  { required: false, message: '请选择' },
                ]}
              >
                {
                  getDicByKey(this.context.dicData, 'dealer', (this.refs.form ? this.refs.form.getFieldsValue(['orgNo']).orgNo : '')) ?
                  (<Tag color="purple">{getDicByKey(this.context.dicData, 'dealer', this.refs.form.getFieldsValue(['orgNo']).orgNo)}</Tag>)
                  : ""
                }
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="激活类型"
                name="activeType"
                rules={[
                  { required: true, message: '请选择' },
                ]}
              >
                <Select
                  disabled={activeTypeDisabled}
                  placeholder="请选择"
                  onChange={handelSelect}
                  getPopupContainer={() => document.getElementById('activeForm')}
                >
                  {newOptions}
                </Select>
              </FormItem>

              <FormItem
                {...formItemLayout}
                style={subDealerVisible}
                label={this.getLabel('是否为二网车辆')}
                name="subDealer"
                rules={[{ validator: this.checkSubDealer }]}
              >
                <RadioGroup onChange={this.onRadioChange} disabled={activeTypeDisabled}>
                  <Radio value={true}>二网车辆</Radio>
                  <Radio value={false}>非二网车辆</Radio>
                </RadioGroup>
              </FormItem>

              <FormItem
                style={qualityVisible}
                {...formItemLayout}
                label={this.getLabel('申报人姓名')}
                name="declarerQuality"
                rules={[{ validator: this.checkDeclarerQuality }]}
              >
                <Select
                  allowClear
                  placeholder="请选择"
                  showSearch
                  filterOption={(input, option) => option.props.title.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                  getPopupContainer={() => document.getElementById('activeForm')}
                  onChange={this.onDeclarerChange}
                >
                  {qualityUserOptions}
                </Select>
              </FormItem>
              <FormItem
                style={declarerVisible}
                {...formItemLayout}
                label={this.getLabel('申报人姓名')}
                name="declarerOther"
                rules={[{ validator: this.checkDeclarerOther }]}
              >
                <Input disabled={realNameDisable} maxLength={20} placeholder="请填写真实姓名" />
              </FormItem>
              <FormItem
                {...formItemLayout}
                style={inputVisible}
                label={this.getLabel('性别')}
                name="sex"
                rules={[{ validator: this.checkSex }]}
              >
                <RadioGroup disabled={realNameDisable}>
                  <Radio value="0">男</Radio>
                  <Radio value="1">女</Radio>
                </RadioGroup>
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="电话号码"
                name="phone"
                rules={[{ required: true, message: '电话号码有误', whitespace: true, pattern: /^1[0-9][0-9]\d{8}$/ }]}
              >
                <Input disabled={phoneDisable} placeholder="请填写电话号码" onBlur={this.setPhoneVal} onChange={this.onChangePhone} onKeyPress={this.resetPhone} />
              </FormItem>
              <FormItem
                label={this.getLabel('验证码')}
                style={codeVisible}
                {...formItemLayout}
                name="captcha"
                rules={[{ validator: this.checkCaptcha }]}
              >
                <Row gutter={24}>
                  {/* <Col span={24}> */}
                    <Col span={15}>
                      <Input
                        placeholder="请填写验证码"
                        //onChange={e => this.setState({ captcha: e.target.value })}
                        //onPressEnter={this.checkedPhone}
                      />
                    </Col>
                    <Col span={8} push={1}>
                      <Button
                        type="primary"
                        disabled={count}
                        onClick={this.onGetCaptcha}
                      >
                        { count ? `${count} s` : '获取验证码' }
                      </Button>
                    </Col>
                  {/* </Col> */}
                </Row>
              </FormItem>
              
              <FormItem
                {...formItemLayout}
                style={subDealerAddressVisible}
                label={this.getLabel('二网地址')}
                name="subDealerAddress"
                rules={[{ validator: this.checkSubDealerAddress }]}
              >
                <TextArea disabled={true} rows={3} maxLength={50} placeholder="请输入" />
              </FormItem>
              <div style={subDealerAddressVisible}>
                <Row >
                  <Col md={8} sm={24} />
                  <Col md={8} sm={24}>
                    <a onClick={()=>this.setState({mapVisible: true})}>点击打开地图选择地址</a>
                  </Col>
                  <Col md={8} sm={24} >
                    <a onClick={()=>this.handleHistoryAddress()}>查看历史地址</a>
                  </Col>
                </Row>
              </div>
              <FormItem
                {...formItemLayout}
                style={dateVisible}
                label={this.getLabel('截止时间')}
                name="expiryDate"
                rules={[{ validator: this.checkDate }]}
              >
                <DatePicker style={{ width: '100%' }} disabledDate={phoneDisable ? this.disabledDeadlineDate : this.disabledDate } disabled={deadlineDisable}/>
              </FormItem>
              <FormItem
                style={inputVisible}
                {...formItemLayout}
                label={'证件类型'}
                // label={this.getLabel('证件类型')}
                name="certType"
                // rules={[{ validator: this.checkCertType }]}
              >
                <Select
                  disabled={realNameDisable}
                  onChange={this.handleCertTypeChange}
                  allowClear
                  placeholder="请选择"
                  getPopupContainer={() => document.getElementById('activeForm')}
                >
                  <Option key="1">居民身份证</Option>
                  <Option key="2">护照</Option>
                  <Option key="3">军官证</Option>
                  <Option key="4">警官证</Option>
                  <Option key="5">统一社会信用代码</Option>
                  <Option key="6">港澳居民来往内地通行证</Option>
                  <Option key="7">台湾居民来往大陆通行证</Option>
                  <Option key="8">其它</Option>
                </Select>
              </FormItem>
              <FormItem
                style={inputVisible}
                {...formItemLayout}
                label={'证件号码'}
                // label={this.getLabel('证件号码')}
                name="certNo"
                rules={[{ validator: this.checkCertNo }]}
              >
                <Input  disabled={realNameDisable} placeholder="请填写证件号码" />
              </FormItem>
              <FormItem
                style={inputVisible}
                {...formItemLayout}
                label={'联系地址'}
                // label={this.getLabel('联系地址')}
                name="address"
                // rules={[{ validator: this.checkAddress }]}
              >
                <Input disabled={realNameDisable} maxLength={250} placeholder="请填写地址" />
              </FormItem>
              <FormItem
                {...formItemLayout}
                style={inputVisible}
                label="紧急联系人姓名"
                name="contactName"
                rules={[
                  { required: false, message: '请填写紧急联系人姓名' },
                ]}
              >
                <Input maxLength={20} placeholder="请填写紧急联系人姓名" />
              </FormItem>
              <FormItem
                {...formItemLayout}
                style={inputVisible}
                label="紧急联系人电话"
                name="contactTel"
                rules={[{ required: false, message: '电话号码有误', whitespace: true, pattern: /^1[0-9][0-9]\d{8}$/ }]}
              >
                <Input placeholder="请填写紧急联系人电话" onBlur={this.setPhoneVal} onKeyPress={this.resetPhone} />
              </FormItem>
              <FormItem
                style={{ ...uploadUrlVisible, marginBottom: '12px'}}
                {...formItemLayout}
                label={this.getLabel(label)}
                name="url1"
                rules={[{ validator: this.checkTemplateFile }]}
              >
                <Upload
                  action={str}
                  headers={{OptAuthorization: `${getToken()}`, ...getOptAuthHeaders()}}
                  listType="picture-card"
                  fileList={fileList}
                  onPreview={this.handlePreview}
                  onChange={this.handleChange}
                  beforeUpload={this.beforeUpload}
                >
                  {fileList.length >= 1 ? null : uploadButton1}
                </Upload>
              </FormItem>
              <Row style={modelVisible}>
                <Col md={6} sm={24} />
                <Col md={12} sm={24}>
                  {
                    activeFileUrl === '' ?
                      <a disabled title="点击下载模板文件" >暂无模板下载</a>
                      :
                      <a href={activeFileUrl} title="点击下载模板文件" >展车工作联络单模板下载</a>}
                </Col>
              </Row>
              <Row style={urlsVisible} gutter={24}>
                <Col lg={6} md={12} sm={24}>
                  <FormItem
                  labelCol={{span: 24}}
                  label={'购车发票'}
                    // label={this.getLabel('购车发票')}
                    name="url2"
                    // rules={[{ validator: this.checkUrl2 }]}
                  >
                    <Upload
                      action={str}
                      headers={{OptAuthorization: `${getToken()}`, ...getOptAuthHeaders()}}
                      listType="picture-card"
                      fileList={url2List}
                      onPreview={this.handlePreview}
                      onChange={this.handleUrl2Change}
                      beforeUpload={this.beforeUpload}
                      showUploadList={showUploadList}
                    >
                      {url2List.length >= 1 ? null : uploadButton}
                    </Upload>
                  </FormItem>
                </Col>
                <Col lg={6} md={12} sm={24}>
                  <FormItem
                  labelCol={{span: 24}}
                    label={'证件正面'}
                    // label={this.getLabel('证件正面')}
                    name="fullFaceUrl"
                    // rules={[{ validator: this.checkFullFaceUrl }]}
                  >
                    <Upload
                      action={fullFaceStr}
                      headers={{OptAuthorization: `${getToken()}`, ...getOptAuthHeaders()}}
                      listType="picture-card"
                      fileList={fullFaceUrlList}
                      onPreview={this.handlePreview}
                      onChange={this.handleFullFaceUrlChange}
                      beforeUpload={this.beforeUpload}
                    >
                      {fullFaceUrlList.length >= 1 ? null : uploadButton}
                    </Upload>
                  </FormItem>
                </Col>
                <Col lg={6} md={12} sm={24}>
                  <FormItem
                  labelCol={{span: 24}}
                   label={'证件反面'}
                    // label={this.getLabel('证件反面')}
                    name="backViewUrl"
                    // rules={[{ validator: this.checkBackViewUrl }]}
                  >
                    <Upload
                      action={backViewStr}
                      headers={{OptAuthorization: `${getToken()}`, ...getOptAuthHeaders()}}
                      listType="picture-card"
                      fileList={backViewUrlList}
                      onPreview={this.handlePreview}
                      onChange={this.handleBackViewUrlChange}
                      beforeUpload={this.beforeUpload}
                    >
                      {backViewUrlList.length >= 1 ? null : uploadButton}
                    </Upload>
                  </FormItem>
                </Col>
                <Col lg={6} md={12} sm={24}>
                  <FormItem
                  labelCol={{span: 24}}
                    label={'手持证件:'}
                    // label={this.getLabel('手持证件')}
                    name="handPhotoUrl"
                    // rules={[{ validator: this.checkHandPhotoUrl }]}
                  >
                    <Upload
                      action={handPhotoStr}
                      headers={{OptAuthorization: `${getToken()}`, ...getOptAuthHeaders()}}
                      listType="picture-card"
                      fileList={handPhotoUrlList}
                      onPreview={this.handlePreview}
                      onChange={this.handleHandPhotoUrlChange}
                      beforeUpload={this.beforeUpload}
                    >
                      {handPhotoUrlList.length >= 1 ? null : uploadButton}
                    </Upload>
                  </FormItem>
                </Col>
              </Row>
              <Row style={businessLicenseVisible} gutter={24}>
                <Col lg={6} md={12} sm={24}>
                  <FormItem
                  labelCol={{span: 22}}
                   label={'营业执照'}
                    // label={this.getLabel('营业执照')}
                    name="businessLicenseUrl"
                    // rules={[{ validator: this.checkBusinessLicenseUrl }]}
                  >
                    <Upload
                      action={str}
                      headers={{OptAuthorization: `${getToken()}`, ...getOptAuthHeaders()}}
                      listType="picture-card"
                      fileList={businessLicenseUrlList}
                      onPreview={this.handlePreview}
                      onChange={this.handleBusinessLicenseUrlChange}
                      beforeUpload={this.beforeUpload}
                      showUploadList={showUploadList}
                    >
                      {businessLicenseUrlList.length >= 1 ? null : uploadButton}
                    </Upload>
                  </FormItem>
                </Col>
              </Row>
              <FormItem
                style={{ display: 'none' }}
                {...formItemLayout}
                label=""
                name="applyId"
                rules={[
                  { required: false, message: '' },
                ]}
              >
                <Input />
              </FormItem>
            </Form>
          </div>
        </Modal>
        <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
          <img alt="" style={{ width: '100%' }} src={previewImage} />
        </Modal>
        <MapSearch
          changeVisible={() => this.setState({mapVisible: false})}
          visible={mapVisible}
          getAddress={this.getAddress}
        />
        <AddressHistoryModal
          ref={address => this.address = address}
          handleSetAddress={this.handleSetAddress}
        />
      </div>
    );
  }


  renderForm() {
    return this.renderSimpleForm();
  }
  render() {
    return (
      <div className={styles.tableListForm}>
        {this.renderForm()}
      </div>
    );
  }
}
